import { ref, nextTick } from 'vue'
import { useChatStore } from '@/stores/chat'
import { useConversationStore } from '@/stores/conversation'
import { sendChatMessage } from '@/service'
import type { VisionFile } from '@/types/app'

export function useStreamingChat() {
  const chatStore = useChatStore()
  const conversationStore = useConversationStore()
  const isResponding = ref(false)
  
  // 添加 AbortController 管理
  let currentAbortController: AbortController | null = null

  /**
   * 发送流式聊天消息的统一接口
   * @param message 消息内容
   * @param files 附带文件
   * @param options 额外配置选项
   */
  const sendStreamingMessage = async (
    message: string,
    files: VisionFile[] = [],
    options: {
      onProgress?: (progress: { chunk: string; totalLength: number }) => void
      onConversationCreated?: (conversationId: string) => void
    } = {}
  ) => {
    if (!message.trim()) return

    console.log('🚀 开始发送流式消息:', { message, filesCount: files.length })

    // 生成唯一消息ID
    const questionId = `question_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
    const answerId = `answer_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`

    try {
      // 1. 添加用户消息到聊天列表
      const userMessage = {
        id: questionId,
        content: message,
        isAnswer: false,
        message_files: files.map(file => ({
          id: file.upload_file_id || '',
          type: file.type,
          url: file.url,
          belongs_to: 'user' as const
        }))
      }
      chatStore.addChatItem(userMessage)

      // 2. 添加AI回复占位符
      const aiMessage = {
        id: answerId,
        content: '',
        isAnswer: true,
        agent_thoughts: [],
        message_files: [],
        streaming: true
      }
      chatStore.addChatItem(aiMessage)

      // 3. 准备API请求数据
      const isNewConversation = !conversationStore.currConversationId || 
                                conversationStore.currConversationId === '-1'
      
      const requestData = {
        query: message,
        user: "abc-123",
        conversation_id: isNewConversation ? '' : conversationStore.currConversationId,
        inputs: {},
        ...(files.length > 0 && {
          files: files.map(file => ({
            type: file.type,
            transfer_method: 'local_file',
            upload_file_id: file.upload_file_id
          }))
        })
      }

      // 4. 设置响应状态
      isResponding.value = true
      const currentConversationId = conversationStore.currConversationId

      // 5. 创建增强的流式处理器
      const streamingHandlers = chatStore.createStreamingHandlers(answerId)
      const enhancedHandlers = createEnhancedHandlers(
        streamingHandlers,
        {
          message,
          isNewConversation,
          currentConversationId,
          answerId,
          onProgress: options.onProgress,
          onConversationCreated: options.onConversationCreated
        }
      )

      // 6. 发送流式请求
      await sendChatMessage(requestData, enhancedHandlers)

      console.log('✅ 流式消息发送完成')
      return { questionId, answerId }

    } catch (error) {
      console.error('❌ 流式消息发送失败:', error)
      isResponding.value = false
      chatStore.endStreaming(answerId, true, '🌐 网络连接失败，请检查网络设置后重试。')
      
      // 清理 AbortController
      currentAbortController = null
      
      throw error
    } finally {
      // 如果不是因为用户中断，则清理状态
      if (currentAbortController) {
        isResponding.value = false
        currentAbortController = null
      }
    }
  }

  /**
   * 创建增强的流式处理器，添加额外的业务逻辑
   */
  const createEnhancedHandlers = (
    baseHandlers: ReturnType<typeof chatStore.createStreamingHandlers>,
    context: {
      message: string
      isNewConversation: boolean
      currentConversationId: string
      answerId: string
      onProgress?: (progress: { chunk: string; totalLength: number }) => void
      onConversationCreated?: (conversationId: string) => void
    }
  ) => {
    let totalLength = 0

    return {
      ...baseHandlers,

      // 获取 AbortController 实例
      getAbortController: (abortController: AbortController) => {
        currentAbortController = abortController
        console.log('📋 获取到 AbortController，可以进行请求中断')
      },

      onData: (chunk: string, isFirst: boolean, moreInfo: any) => {
        console.log('📥 收到流式数据:', { 
          chunk: chunk.substring(0, 50) + (chunk.length > 50 ? '...' : ''),
          chunkLength: chunk.length,
          isFirst 
        })

        // 处理对话管理
        if (moreInfo.conversationId && moreInfo.conversationId !== context.currentConversationId) {
          context.currentConversationId = moreInfo.conversationId
          conversationStore.setCurrConversationId(context.currentConversationId)

          // 新对话创建回调
          context.onConversationCreated?.(context.currentConversationId)

          // 如果是新对话，添加到对话列表
          if (context.isNewConversation) {
            const newConversation = {
              id: context.currentConversationId,
              name: context.message.length > 20 
                ? context.message.substring(0, 20) + '...' 
                : context.message,
              created_at: new Date().toISOString()
            }
            conversationStore.addConversation(newConversation)
          }
        }

        // 调用基础处理器
        baseHandlers.onData(chunk, isFirst, moreInfo)

        // 更新总长度并触发进度回调
        if (isFirst) {
          totalLength = chunk.length
        } else {
          totalLength += chunk.length
        }
        
        context.onProgress?.({ chunk, totalLength })

        // 自动滚动到底部
        autoScrollToBottom()
      },

      onCompleted: (hasError?: boolean) => {
        console.log('🎉 流式消息完成:', { hasError, totalLength })
        isResponding.value = false
        currentAbortController = null
        baseHandlers.onCompleted(hasError)
      },

      onError: (error: string) => {
        console.error('💥 流式消息错误:', error)
        isResponding.value = false
        currentAbortController = null
        baseHandlers.onError(error)
      }
    }
  }

  /**
   * 自动滚动到聊天底部
   */
  const autoScrollToBottom = () => {
    nextTick(() => {
      const containers = [
        '.chat-interface .flex-1',
        '.chat-messages',
        '[data-chat-container]'
      ]
      
      for (const selector of containers) {
        const element = document.querySelector(selector)
        if (element) {
          element.scrollTop = element.scrollHeight
          break
        }
      }
    })
  }

  /**
   * 中断当前流式响应
   */
  const abortStreaming = () => {
    console.log('🛑 用户请求中断流式响应')
    
    // 中断网络请求
    if (currentAbortController) {
      currentAbortController.abort()
      console.log('📡 已中断网络请求')
    }
    
    // 更新UI状态
    if (chatStore.currentStreamingMessageId) {
      chatStore.endStreaming(
        chatStore.currentStreamingMessageId, 
        true, 
        '⏹️ 用户中止了响应'
      )
    }
    
    // 重置状态
    isResponding.value = false
    currentAbortController = null
    
    console.log('✅ 流式响应已完全中断')
  }

  /**
   * 重新生成最后一条AI回复
   */
  const regenerateLastResponse = async () => {
    const lastUserMessage = [...chatStore.chatList]
      .reverse()
      .find(item => !item.isAnswer)

    if (!lastUserMessage) {
      console.warn('⚠️ 未找到用户消息，无法重新生成')
      return
    }

    // 移除最后一条AI回复 - 使用传统方法查找最后一个索引
    let lastAiMessageIndex = -1
    for (let i = chatStore.chatList.length - 1; i >= 0; i--) {
      if (chatStore.chatList[i].isAnswer) {
        lastAiMessageIndex = i
        break
      }
    }
    
    if (lastAiMessageIndex !== -1) {
      chatStore.chatList.splice(lastAiMessageIndex, 1)
    }

    // 重新发送消息
    await sendStreamingMessage(
      lastUserMessage.content,
      lastUserMessage.message_files?.map(file => ({
        upload_file_id: file.id,
        type: file.type,
        url: file.url
      })) || []
    )
  }

  return {
    // 状态
    isResponding,
    currentStreamingMessage: chatStore.currentStreamingMessage,
    isStreaming: chatStore.isStreaming,

    // 方法
    sendStreamingMessage,
    abortStreaming,
    regenerateLastResponse,
    autoScrollToBottom
  }
} 